package com.mt.vsphere.core.util;

import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class CommonUtil {


    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }
    /**
     * 获取；两个日期中间的日期
     * @return List
     */
    public static List<String> getBetweenDate(String start,String end){
        LocalDate startDay = LocalDate.parse(start);
        LocalDate endDay = LocalDate.parse(end);
        long distance = ChronoUnit.DAYS.between(startDay, endDay);
        List<String> list = new ArrayList<>((int)distance);
        Stream.iterate(startDay, d -> {
            return d.plusDays(1);
        }).limit(distance + 1).forEach(f -> {
            list.add(f.toString());
        });
        return list;
    }

    public static boolean canParseInt(String str){
        if(str == null){
            return false;
        }
        return str.matches("\\d+");
    }

    //获取随机值
    public static int getRandomCount(int limit){
        return (int) (limit*Math.random());
    }

    public static String getTimeOld(Timestamp time){
        long addTime = time.getTime();
        long nowTime = Timestamp.valueOf(LocalDateTime.now()).getTime();
        String msg = "";

        long dateTemp1 = (nowTime-addTime) / 1000; // 秒
        long dateTemp2 = dateTemp1 / 60; // 分钟
        long dateTemp3 = dateTemp2 / 60; // 小时
        long dateTemp4 = dateTemp3 / 24; // 天数
        long dateTemp5 = dateTemp4 / 30; // 月数
        long dateTemp6 = dateTemp5 / 12; // 年数
        if (dateTemp6 > 0) {
            msg = dateTemp6 + "年前";
        } else if (dateTemp5 > 0) {
            msg = dateTemp5 + "个月前";
        } else if (dateTemp4 > 0) {
            msg = dateTemp4 + "天前";
        } else if (dateTemp3 > 0) {
            msg = dateTemp3 + "小时前";
        } else if (dateTemp2 > 0) {
            msg = dateTemp2 + "分钟前";
        } else if (dateTemp1 > 0) {
            msg = "刚刚";
        }
        return msg;
    }
    public static String getTimeOldStr(Timestamp time){
        long addTime = time.getTime();
        long nowTime = Timestamp.valueOf(LocalDateTime.now()).getTime();
        String msg = "";

        long dateTemp1 = (nowTime-addTime) / 1000; // 秒
        long dateTemp2 = dateTemp1 / 60; // 分钟
        long dateTemp3 = dateTemp2 / 60; // 小时
        long dateTemp4 = dateTemp3 / 24; // 天数
        long dateTemp5 = dateTemp4 / 30; // 月数
        long dateTemp6 = dateTemp5 / 12; // 年数
        if (dateTemp6 > 0 ||dateTemp5 > 0||dateTemp4 > 0) {
            msg = time.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } else if (dateTemp3 > 0) {
            msg = dateTemp3 + "小时前";
        } else if (dateTemp2 > 0) {
            msg = dateTemp2 + "分钟前";
        } else if (dateTemp1 > 0) {
            msg = "刚刚";
        }
        return msg;
    }


    public static String getItemID( int n )
    {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for ( int i = 0; i < n; i++ )
        {
            String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
            if ( "char".equalsIgnoreCase( str ) )
            { // 产生字母
                int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
                // System.out.println(nextInt + "!!!!"); 1,0,1,1,1,0,0
                val.append((char) (nextInt + random.nextInt(26)));
            }
            else { // 产生数字
                val.append(String.valueOf(random.nextInt(10)));
            }
        }
        return val.toString();
    }

    public static String filterSpecialCharAndUpper(String s){
        s = s.replaceAll("[^0-9a-zA-Z-]","");
        return s.toUpperCase();
    }

    public static List<byte[]> md5ToByte(String base64Img){
        List<byte[]> list = new ArrayList<>();
        if (base64Img.equals("")){
            return list;
        }
        String[] str = base64Img.split("##");
        BASE64Decoder decoder = new BASE64Decoder();
        for (String base64Str:str){
            //Base64解码
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(base64Str);

            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {
                    //调整异常数据
                    b[i]+=256;
                }
            }
            list.add(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    //获取中文时间格式化
    public static String getDayTimeFormatCn(long dayTime){
        return new SimpleDateFormat("MM月dd日 ").format(new Date(dayTime * 1000));
    }

    //获取中文时间格式化
    public static String getDayTimeAndTimeFormatCn(long dayTime){
        return new SimpleDateFormat("MM月dd日 HH:mm").format(new Date(dayTime * 1000));
    }
    //java字段转化为数据库
    public static String changeFieldToColumnName(String fieldName) {
        if(fieldName==null){
            return null;
        }
        StringBuilder columnName = new StringBuilder();
        int length = fieldName.length();
        for(int i=0;i<length;i++){
            char c = fieldName.charAt(i);
            if('A'<=c && 'Z'>=c){
                columnName.append("_").append((char)(c+32));
            }else{
                columnName.append(fieldName.charAt(i));
            }
        }
        return columnName.toString();
    }


    //把数字变成中文单位的
    public static String changeNumToCnStr(Integer num){
        String numStr = num.toString();
        if (numStr.length() < 5){
            //千位以内
            return numStr;
        }else if (numStr.length() < 9){
            //万位以内
            float d = ((float)num/10000f);
            DecimalFormat df = new DecimalFormat("#.0万");
            return df.format(d);
        }else {
            //亿位以内
            float d = ((float)num/100000000f);
            DecimalFormat df = new DecimalFormat("#.0亿");
            return df.format(d);
        }

    }

    public static void main(String[] args) {
        float d = ((float)1111111/10000f);

        DecimalFormat df = new DecimalFormat("#.0万");
        String str = df.format(d);
        System.out.println(str);
    }
    //是否包含在str列表中
    public static boolean isContailStrList(String strList,String str){
        strList = ","+strList+",";
        return strList.contains(","+str+",");
    }
//    public static void main(String[] args) {
//        System.out.println(getDayTimeFormatCn(System.currentTimeMillis()/1000));
//    }
}
